#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <net/if.h>

#define CAN_INTERFACE "can0"  // 这里设置你使用的 CAN 接口

// 函数：设置 CAN 接口
int setup_can_socket(const char *interface_name) {
    struct ifreq ifr;
    struct sockaddr_can addr;
    int s;

    // 创建一个 socket
    s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
    if (s < 0) {
        perror("Socket creation failed");
        return -1;
    }

    // 获取 CAN 接口信息
    strncpy(ifr.ifr_name, interface_name, sizeof(ifr.ifr_name) - 1);
    if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
        perror("IOCTL failed to get interface index");
        close(s);
        return -1;
    }

    // 设置 sockaddr_can
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;

    // 绑定 socket 到指定的 CAN 接口
    if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
        perror("Bind failed");
        close(s);
        return -1;
    }

    return s;
}

// 函数：发送 CAN 帧
void send_can_frame(int socket, unsigned int can_id, unsigned char *data, unsigned int data_len) {
    struct can_frame frame;

    // 设置 CAN 帧 ID 和数据
    frame.can_id = can_id;
    frame.can_dlc = data_len;
    memcpy(frame.data, data, data_len);

    // 发送 CAN 帧
    if (write(socket, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
        perror("Write failed");
    }
}

int main() {
    int socket;
    unsigned char data1[] = {0x01, 0x02, 0x03, 0x04};  // 第一个数据帧
    unsigned char data2[] = {0x05, 0x06, 0x07, 0x08};  // 第二个数据帧
    unsigned char data3[] = {0x09, 0x0A, 0x0B, 0x0C};  // 第三个数据帧

    // 设置 CAN socket
    socket = setup_can_socket(CAN_INTERFACE);
    if (socket < 0) {
        return -1;
    }

    // 发送 3 个数据帧
    printf("Sending CAN frame 1...\n");
    send_can_frame(socket, 0x123, data1, sizeof(data1));  // CAN ID 0x123, 数据 data1

    printf("Sending CAN frame 2...\n");
    send_can_frame(socket, 0x124, data2, sizeof(data2));  // CAN ID 0x124, 数据 data2

    printf("Sending CAN frame 3...\n");
    send_can_frame(socket, 0x125, data3, sizeof(data3));  // CAN ID 0x125, 数据 data3

    // 关闭 socket
    close(socket);

    return 0;
}

